package com.stwitinc.redmine.dao;

import java.io.File;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.stwitinc.config.ConfigManager;
import com.stwitinc.data.DataAccessObject;
import com.stwitinc.data.DbOperator;
import com.stwitinc.data.model.DbModel;
import com.stwitinc.util.ClassMapping;
import com.stwitinc.xmlobjects.config.DataSource;

public abstract class DAO extends DataAccessObject
{
	private static ComboPooledDataSource dataSource;
	private static ClassMapping classMapping = new ClassMapping("/com/stwitinc/redmine/dao/Mapping.properties");

	public static void destroy() {
		dataSource.close();
	}

	public static ComboPooledDataSource getDataSource() {
		return dataSource;
	}

	public static void init() {
		/*DataSource ds = ConfigManager.getDataSource("stw_news");*/
		DataSource ds = ConfigManager.getDataSource("redmine");
		dataSource = new ComboPooledDataSource();
		try {
			dataSource.setDriverClass(ds.getDriver());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		dataSource.setJdbcUrl(ds.getURL());
		dataSource.setUser(ds.getUser());
		dataSource.setPassword(ds.getPassword().getValue());
	}

	public static void main(String[] args) throws Exception {
		/*DbOperator dbo = new DbOperator(ConfigManager.getDataSource("stw_news"));
		File javaHome = new File("D:\\DeveloperTools\\jdk-x64\\jdk1.6.0_45");
		File jarFile = new File("WebContent\\WEB-INF\\lib\\stw-news-db.jar");
		DbModel.generateDbModelJar(dbo.getConnection(), new String[] { "stw_news" }, javaHome, jarFile);*/
		
		
		DbOperator dbo = new DbOperator(ConfigManager.getDataSource("redmine"));
		File javaHome = new File("C:\\Program Files (x86)\\Java\\jdk1.6.0_45");
		File jarFile = new File("WebContent\\WEB-INF\\lib\\stw-redmine-db.jar");
		DbModel.generateDbModelJar(dbo.getConnection(), new String[] { "stw_redmine" }, javaHome, jarFile);
		dbo.close();
	}

	public static MedicineDAO newMedicineDAO() {
		return classMapping.newInstance(MedicineDAO.class);
	}

	public static NewsDAO newNewsDAO() {
		return classMapping.newInstance(NewsDAO.class);
	}

	public static UserDAO newUserDAO() {
		return classMapping.newInstance(UserDAO.class);
	}
	
	public static IssueDAO newIssueDAO(){
		return classMapping.newInstance(IssueDAO.class);
	}

	@Override
	public DbOperator getDbOperator() throws SQLException {
		return new DbOperator(dataSource);
	}
}
